added samples
[windows-sources.git] / sdk / samples / all in on code / Visual Studio 2008 / CppWindowsService / ReadMe.txt
blobe38040430c3a85b8106079b2828a5a8caae4d6d1
1 =============================================================================
2           SERVICE APPLICATION : CppWindowsService Project Overview
3 =============================================================================
5 /////////////////////////////////////////////////////////////////////////////
6 Summary:
8 This code sample demonstrates creating a very basic Windows Service 
9 application in Visual C++. The example Windows Service logs the service start 
10 and stop information to the Application event log, and shows how to run the 
11 main function of the service in a thread pool worker thread. You can easily 
12 extend the Windows Service skeleton to meet your own business requirement.
15 /////////////////////////////////////////////////////////////////////////////
16 Demo:
18 The following steps walk through a demonstration of the Windows Service 
19 sample.
21 Step1. After you successfully build the sample project in Visual Studio 2008, 
22 you will get a service application: CppWindowsService.exe. 
24 Step2. Run a command prompt as administrator, navigate to the output folder 
25 of the sample project, and enter the following command to install the service.
27   CppWindowsService.exe -install
29 The service is successfully installed if the process outputs:
31   CppWindowsService is installed.
33 If you do not see this output, please look for error codes in the ouput, and 
34 investigate the cause of failure. For example, the error code 0x431 means 
35 that the service already exists, and you need to uninstall it first. 
37 Step3. Open Service Management Console (services.msc). You should be able to 
38 find "CppWindowsService Sample Service" in the service list. 
40 Step4. Right-click the CppWindowsService service in Service Management 
41 Console and select Start to start the service. Open Event Viewer, and 
42 navigate to Windows Logs / Application. You should be able to see this event 
43 from CppWindowsService with the information:
45   CppWindowsService
46   CppWindowsService in OnStart
48 Step5. Right-click the service in Service Management Console and select Stop 
49 to stop the service. You will see this new event from CppWindowsService in 
50 Event Viewer / Windows Logs / Application with the information:
52   CppWindowsService
53   CppWindowsService in OnStop
55 Step6. To uninstall the service, enter the following command in the command 
56 prompt running as administrator.
58   CppWindowsService.exe -remove
60 If the service is successfully removed, you would see this output:
62   CppWindowsService is removed.
65 /////////////////////////////////////////////////////////////////////////////
66 Deployment:
68 A. Setup
70 CppWindowsService.exe -install
71 It installs CppWindowsService.exe as a service to the local service control 
72 manager database.
74 B. Cleanup
75 CppWindowsService.exe -remove
76 It stops and removes the CppWindowsService service from the local service 
77 control manager database.
80 /////////////////////////////////////////////////////////////////////////////
81 Creation:
83 Step1. In Visual Studio 2008, add a new Visual C++ / Win32 / Win32 Console 
84 Application project named CppWindowsService. Unselect the "Precompiled 
85 header" option in Application Settings of the Win32 Application Wizard, and 
86 delete stdafx.h, stdafx.cpp, targetver.h files after the project is created. 
88 Step2. Define the settings of the service in CppWindowsService.cpp.
90     // Internal name of the service
91     #define SERVICE_NAME             L"CppWindowsService"
93     // Displayed name of the service
94     #define SERVICE_DISPLAY_NAME     L"CppWindowsService Sample Service"
96     // Service start options.
97     #define SERVICE_START_TYPE       SERVICE_DEMAND_START
99     // List of service dependencies - "dep1\0dep2\0\0"
100     #define SERVICE_DEPENDENCIES     L""
102     // The name of the account under which the service should run
103     #define SERVICE_ACCOUNT          L"NT AUTHORITY\\LocalService"
105     // The password to the service account name
106     #define SERVICE_PASSWORD         NULL
108 Security Note: In this code sample, the service is configured to run as 
109 LocalService, instead of LocalSystem. The LocalSystem account has broad 
110 permissions. Use the LocalSystem account with caution, because it might 
111 increase your risk of attacks from malicious software. For tasks that do 
112 not need broad permissions, consider using the LocalService account, which 
113 acts as a non-privileged user on the local computer and presents anonymous 
114 credentials to any remote server.
116 Step3. Replace the application's entry point (main) in CppWindowsService.cpp 
117 with the code below. According to the arguments in the command line, the 
118 function installs or uninstalls or starts the service by calling into 
119 different routines that will be declared and implemented in the next steps. 
121     int wmain(int argc, wchar_t *argv[])
122     {
123         if ((argc > 1) && ((*argv[1] == L'-' || (*argv[1] == L'/'))))
124         {
125             if (_wcsicmp(L"install", argv[1] + 1) == 0)
126             {
127                 // Install the service when the command is 
128                 // "-install" or "/install".
129                 InstallService(
130                     SERVICE_NAME,               // Name of service
131                     SERVICE_DISPLAY_NAME,       // Name to display
132                     SERVICE_START_TYPE,         // Service start type
133                     SERVICE_DEPENDENCIES,       // Dependencies
134                     SERVICE_ACCOUNT,            // Service running account
135                     SERVICE_PASSWORD            // Password of the account
136                     );
137             }
138             else if (_wcsicmp(L"remove", argv[1] + 1) == 0)
139             {
140                 // Uninstall the service when the command is 
141                 // "-remove" or "/remove".
142                 UninstallService(SERVICE_NAME);
143             }
144         }
145         else
146         {
147             wprintf(L"Parameters:\n");
148             wprintf(L" -install  to install the service.\n");
149             wprintf(L" -remove   to remove the service.\n");
151             CSampleService service(SERVICE_NAME);
152             if (!CServiceBase::Run(service))
153             {
154                 wprintf(L"Service failed to run w/err 0x%08lx\n", GetLastError());
155             }
156         }
158         return 0;
159     }
161 Step4. Add the ServiceBase.h and ServiceBase.cpp files to provide a base 
162 class for a service that will exist as part of a service application. The 
163 class is named "CServiceBase". It must be derived from when creating a new 
164 service class.
166 The service base class has these public functions:
168     // It register the executable for a service with SCM.
169     static BOOL CServiceBase::Run(CServiceBase &service)
171     // This is the constructor of the service class. The optional parameters 
172     // (fCanStop, fCanShutdown and fCanPauseContinue) allow you to specify 
173     // whether the service can be stopped, paused and continued, or be 
174     // notified when system shutdown occurs.
175     CServiceBase::CServiceBase(PWSTR pszServiceName, 
176         BOOL fCanStop = TRUE, 
177         BOOL fCanShutdown = TRUE, 
178         BOOL fCanPauseContinue = FALSE)
180     // This is the virtual destructor of the service class.
181     virtual ~CServiceBase::CServiceBase(void);
182     
183     // Funtion that stops the service.
184     void CServiceBase::Stop();
185     
186 The class also provides these virtual member functions. You can implement 
187 them in a derived class. The functions execute when the service starts, stops, 
188 pauses, resumes, and when the system is shutting down.
190     virtual void OnStart(DWORD dwArgc, PWSTR *pszArgv);
191     virtual void OnStop();
192     virtual void OnPause();
193     virtual void OnContinue();
194     virtual void OnShutdown();
196 Step5. Add the SampleService.h and SampleService.cpp files to provide a 
197 sample service class that derives from the service base class - CServiceBase. 
198 The sample service logs the service start and stop information to the 
199 Application log, and shows how to run the main function of the service in a 
200 thread pool worker thread.
202 CSampleService::OnStart, which is executed when the service starts, calls 
203 CServiceBase::WriteEventLogEntry to log the service-start information. And it 
204 calls CThreadPool::QueueUserWorkItem to queue the main service function 
205 (CSampleService::ServiceWorkerThread) for execution in a worker thread.
207 NOTE: A service application is designed to be long running. Therefore, it 
208 usually polls or monitors something in the system. The monitoring is set up 
209 in the OnStart method. However, OnStart does not actually do the monitoring. 
210 The OnStart method must return to the operating system after the service's 
211 operation has begun. It must not loop forever or block. To set up a simple 
212 monitoring mechanism, one general solution is to create a timer in OnStart. 
213 The timer would then raise events in your code periodically, at which time 
214 your service could do its monitoring. The other solution is to spawn a new 
215 thread to perform the main service functions, which is demonstrated in this 
216 code sample.
218     void CSampleService::OnStart(DWORD dwArgc, LPWSTR *lpszArgv)
219     {
220         // Log a service start message to the Application log.
221         WriteEventLogEntry(L"CppWindowsService in OnStart", 
222             EVENTLOG_INFORMATION_TYPE);
224         // Queue the main service function for execution in a worker thread.
225         CThreadPool::QueueUserWorkItem(&CSampleService::ServiceWorkerThread, this);
226     }
228 CSampleService::OnStop, which is executed when the service stops, calls 
229 CServiceBase::WriteEventLogEntry to log the service-stop information. Next, 
230 it sets the member varaible m_fStopping as TRUE to indicate that the service 
231 is stopping and waits for the finish of the main service function that is 
232 signaled by the m_hStoppedEvent event object.
234     void CSampleService::OnStop()
235     {
236         WriteEventLogEntry(L"CppWindowsService in OnStop", 
237             EVENTLOG_INFORMATION_TYPE);
239         // Indicate that the service is stopping and wait for the finish of the 
240         // main service function (ServiceWorkerThread).
241         m_fStopping = TRUE;
242         if (WaitForSingleObject(m_hStoppedEvent, INFINITE) != WAIT_OBJECT_0)
243         {
244             throw GetLastError();
245         }
246     }
248 CSampleService::ServiceWorkerThread runs in a thread pool worker thread. It 
249 performs the main function of the service such as the communication with 
250 client applications through a named pipe. In order that the main function 
251 finishes gracefully when the service is about to stop, it should periodically 
252 check the m_fStopping varaible. When the function detects that the service is 
253 stopping, it cleans up the work and signal the m_hStoppedEvent event object.
255     void CSampleService::ServiceWorkerThread(void)
256     {
257         // Periodically check if the service is stopping.
258         while (!m_fStopping)
259         {
260             // Perform main service function here...
262             ::Sleep(2000);  // Simulate some lengthy operations.
263         }
265         // Signal the stopped event.
266         SetEvent(m_hStoppedEvent);
267     }
269 Step6. Add the ServiceInstaller.h and ServiceInstaller.cpp files to declare 
270 and implement functions that install and uninstall the service:
272   InstallService          Installs the service
273   UninstallService        Uninstalls the service 
276 /////////////////////////////////////////////////////////////////////////////
277 References:
279 MSDN: About Services
280 http://msdn.microsoft.com/en-us/library/ms681921(VS.85).aspx
282 MSDN: The Complete Service Sample 
283 http://msdn.microsoft.com/en-us/library/bb540476(VS.85).aspx
285 MSDN: Creating a Simple Win32 Service in C++
286 http://msdn.microsoft.com/en-us/library/ms810429.aspx
289 /////////////////////////////////////////////////////////////////////////////